var ns, bmLocation, toast;
app = new Vue({
    el: '#app',
    data: {
        list: [],
        form: {
            ID: 0,
            pageindex: 0,
            pagesize: 10,
            // status: 1, // 1-任务列表 2-新增记录
            PlanType: 1,
            TaskStatus:5,//0-未开始,1-进行中,2-已结束
            planTypeList:1,
        },
        total: {
            ProcessCount: 0,
        },
        current_item_length: 0,
        is_searching: false,
        scroll_top: 0,
        can_scroll: false,
        showTop:false,
        showsearch:false,
        number:0,
        selectlist:[],
        showsearchresult:false,
        searchresult:'',
        checkbox:false,
        choosetype:{},
        choosetaskmodel:{},
        optionName:'',
        choosesortmodel:{},
        option2: [],
        option3: [
            // { text: '排序', value: 0 },
            { text: '时间近到远', value: 1 },
            { text: '时间远到近', value: 2 },
        ],
        menuType: [
            { type: 1, text: '全部类型', value: 0 },
            { type: 2, text: '设备巡检', value: 1 },
            { type: 3, text: '设备维保', value: 2 },
        ],
        OrderByType:1,
        //在线、离线模式
        lineStatus:0,//0 在线  1离线
        offList:[],
    },
    methods: {
        get_data: function () {
            var that = this;
            that.is_searching= true;
            that.can_scroll = false;
            var options = {};
            options.action = "getdeviceplantasklist";
            options.pagesize = that.form.pagesize;
            options.pageindex = that.form.pageindex;
            options.Status = that.form.TaskStatus;
            options.OrderByType = that.OrderByType;
            options.Type = that.form.PlanType;
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                // console.log(JSON.stringify(data));
                that.is_searching = false;
                if (succeed) {

                    if (data.listHandle.length == that.form.pagesize) {
                        that.can_scroll = true;
                    }
                    if (that.form.pageindex == 0) {
                        that.selectlist = data.listHandle;
                    } else {
                        that.selectlist = that.selectlist.concat(data.listHandle);
                    }

                    app.current_item_length = that.selectlist.length
                    // that.total.ProcessCount = data.ProcessCount;
                    // that.number=data.number;
                    // for(var i=0;i<data.list.length;i++){
                    //     data.list[i].JpushAddTime = ns.SetTime_style(data.list[i].JpushAddTime);
                    // }

                } else if (err) {
                    that.current_item_length = 0;
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        //获取筛选条件
        get_menuType: function () {
            var that = this;
            var options = {};
            options.action = 'getdeviceplantasksearchparams';
            options.Type = 1;
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    if (data.status) {
                        that.option2 = data.list;
                        that.choosetaskmodel = data.list[1];
                        that.optionName = that.choosetaskmodel.Name + '(' + that.choosetaskmodel.Number + ')';
                        that.choosetype = that.menuType[0];
                        that.choosesortmodel = that.option3[0];
                    }
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            })
        },
        //翻页第一条数据的位置
        do_scrollbtn: function (id) {
            var sollid = document.getElementById('scroll' + id);
            window.scrollTo(0, sollid.offsetTop);
        },
        select_status: function (status) {
            var that = this;
            that.showTop = false;
            that.form.pageindex = 0;
            that.showsearchresult = true;
            if (status == 1) {
                that.searchresult = "设备巡检";
                that.form.planTypeList = [1];
            }
            if (status == 2) {
                that.searchresult = "设备维保";
                that.form.planTypeList = [2];
            }
            that.list = [];
            that.get_data();
        },
        onChooseType: function (item) {
            var that = this;
            that.choosetype = item;
            this.$refs.choosetype.toggle();
            that.form.PlanType = item.type;
            that.form.pageindex = 0;
            that.form.pagesize = 10;
            that.get_data();
        },
        onChooseTask: function (item) {
            var that = this;
            that.choosetaskmodel = item;
            that.optionName = that.choosetaskmodel.Name + '(' + that.choosetaskmodel.Number + ')';
            this.$refs.choosetask.toggle();
            that.form.TaskStatus = item.Type;
            that.form.pageindex = 0;
            that.form.pagesize = 10;
            that.get_data();
        },
        onChooseSort: function (item) {
            var that = this;
            that.choosesortmodel = item;
            this.$refs.choosesort.toggle();
            that.OrderByType = item.value;
            that.form.pageindex = 0;
            that.form.pagesize = 10;
            that.get_data();
        },
        open_list: function (item) {
            var that = this;
            var url = 'equipment_list_frm';
            var title = item.DevicePlanName;
            ns.openWin(url, title, {
                id: item.ID
            });
        },
        open_select: function () {
            var that = this;
            that.showTop = !that.showTop;
        },
        open_add: function () {
            var that = this;
            ns.openWin('equipment_addfrm', '新增记录');
        },
        doHideSearch: function () {
            var that = this;
            that.showTop = false;
            that.showsearch = false;
        },
        do_closearch: function () {
            var that = this;
            that.showsearch = false;
            that.showTop = false;
            that.showsearchresult = false;
            that.form.planTypeList = [1, 2];
            that.list = [];
            that.get_data();
        },
        select_allstatus: function () {
            var that = this;
            that.showsearch = !that.showsearch;
            // that.form.planTypeList=[1,2];
            var options = {};
            options.planTypeList = JSON.stringify(that.form.planTypeList);
            options.action = "getdeviceplantaskpendinghandlelist";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.selectlist = data.list;
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        do_scrollTo: function () {
            var that = this;
            var sollid = document.getElementById('scroll' + that.form.ID);
            window.scrollTo(0, sollid.offsetTop);
            var classlist = document.getElementById('scroll' + that.form.ID).getElementsByClassName('boxbg')[0];
            classlist.style.backgroundColor = "#eaf1ff";
            setTimeout(function () {
                classlist.style.backgroundColor = "#f7fbff";
            }, 800)
        },
         //在线-离线模式切换
         open_change_line: function () {
            let that=this;
            //获取当前网络状态
            api.getNetworkType({
                success: function(res) {
                    if(res.networkType!="none"){
                        //有网  当离线切换在线时  任务存在需要判断是否上传任务  上传成功后需要清空任务
                        //有网  当在线切换离线时  覆盖并创建任务
                        let message= that.lineStatus==0?'离线':'在线';
                        api.confirm({
                            title: '提示',
                            msg: '是否切换'+message+'模式?',
                            buttons: ['确定', '取消']
                        }, function(ret, err) {
                            if (ret.buttonIndex == 1) {
                                that.lineStatus=1;
                                that.get_data_off();
                                api.setPrefs({
                                    key: 'lineStatus_equipment',
                                    value: 1
                                });
                            }
                            if (ret.buttonIndex == 2) {
                                that.lineStatus=0;
                                that.get_data();  
                                api.setPrefs({
                                    key: 'lineStatus_equipment',
                                    value: 0
                                }); 
                            }     
                        });
                    }else{
                        api.toast({
                            msg: '请联网，只能在有网的情况下进行模式切换！',
                            duration: 2000,
                            location: 'bottom'
                        });
                        return;
                    }   
                }
            });
        },
        //离线模式
        get_data_off: function () {
            //创建 任务表、巡更点打卡表、附件表
            var that = this;
            var options = {};
            options.action = "getofftasklist";
            options.Type = that.form.planTypeList;
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                // console.log(JSON.stringify(data));
                if (succeed) {
                    that.offList = data.listHandle;
                    that.configList=data.listConfig;
                    if(that.offList.length>0){
                       let res=that.set_create_off();
                       if (res) {
                            api.addEventListener({
                                name: 'viewdisappear'
                            }, function (ret, err) {
                                api.closeWin();
                            });
                            ns.openWin('renwulist_equipment_offlist', "设备作业待办(离线模式)");
                        }
                    }
                    else{
                        api.toast({
                            msg: "暂无待办需要处理的数据，未创建离线任务",
                            duration: 2000,
                            location: 'bottom'
                        });
                        that.lineStatus = 0;
                        that.get_data();
                        api.setPrefs({
                            key: 'lineStatus_equipment',
                            value: 0
                        }); 
                    }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        set_create_off: function () {
            var that = this;     
            that.offList.forEach((item, index) => {
                //先执行删除-再执行插入-保持最新数据
                let delstandardsql=`DELETE FROM Sys_TaskStandard WHERE PlanTaskID=${item.ID}`;    
                let delfilesql=`DELETE FROM Sys_File WHERE PlanTaskID=${item.ID}`;
                let deltasksql=`DELETE FROM Sys_PlanTask WHERE PlanTaskID=${item.ID}`;
                let delplansql=`DELETE FROM Sys_Plan WHERE ID=${item.ID}`;    
                db.executeSql({
                    name: 'prodemotest',
                    sql: delstandardsql,
                }, function (ret, err) {
                });    
                db.executeSql({
                    name: 'prodemotest',
                    sql: delfilesql,
                }, function (ret, err) {
                });
                db.executeSql({
                    name: 'prodemotest',
                    sql: deltasksql,
                }, function (ret, err) {
                });
                db.executeSql({
                    name: 'prodemotest',
                    sql: delplansql,
                }, function (ret, err) {
                });   
                var nowdate=moment().format('YYYY-MM-DD HH:mm:ss');
                //插入Sys_Plan 表数据
                let plansql = `INSERT INTO Sys_Plan (ID,DevicePlanName,ProjectID,ProjectName,PlanType,PlanTypeDesc,TaskStatus,TaskResultDesc,OutTimeStatusDesc,TaskStatusDesc,StartTime,EndTime,CheckStartTime,CheckEndTime,TaskChargeManName,WorkOrderType,PatrolLineName,count,completeCount,normalCount,abnormalCount,IsUpload,UploadTime,IsAllowCard,IsMiss,WithLine) VALUES (${item.ID},'${item.DevicePlanName}',${item.ProjectID},'${item.ProjectName}',${item.PlanType},'${item.PlanTypeDesc}',${item.TaskStatus},'${item.TaskResultDesc}','${item.OutTimeStatusDesc}','${item.TaskStatusDesc}','${item.StartTime}','${item.EndTime}','${item.CheckStartTime}','${item.CheckEndTime}','${item.TaskChargeManName}',${item.WorkOrderType},'${item.PatrolLineName}',${item.count},${item.completeCount},${item.normalCount},${item.abnormalCount},0,'${nowdate}','${item.IsAllowCard}','${item.IsMiss}',${item.WithLine});`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: plansql,
                }, function (ret, err) { 
                });
                if (item.TaskList != undefined && item.TaskList.length > 0) {
                    item.TaskList.forEach((itemtask, indextask) => {
                        //插入Sys_PlanTask 表数据
                        let CheckStatusDesc=itemtask.IsInvalidComplete? 2 : 1;
                        let tasksql = `INSERT INTO Sys_PlanTask (EncriptID,ID,ProjectName,PatrolNumber,PatrolID,PatrolName,RequireScan, CanProcessDirect,IsAllowUpload,IsAllowGPS,TaskStatus,TaskResultDesc,IsInvalidComplete,StartTime,GPSLocation,CanPunchCard,IsAllowCard,IsSupplementCard,IsMiss,TaskChargeManID,TaskChargeManName,TaskChargeManHeaderImg,IsAbnormal,IsReport,GongdanType,GongdanTypeDesc,GongdanID,PlanTaskID,CheckStatus,TaskCompleteContent,TaskCompleteTime,Longitude,Latitude,APPUpload,DeviceModel,DeviceLocationPlace) VALUES ('${itemtask.EncriptID}',${itemtask.ID},'${itemtask.ProjectName}','${itemtask.PatrolNumber}',${itemtask.PatrolID},'${itemtask.PatrolName}','${itemtask.RequireScan}','${itemtask.CanProcessDirect}','${itemtask.IsAllowUpload}','${itemtask.IsAllowGPS}',${itemtask.TaskStatus},'${itemtask.TaskResultDesc}','${itemtask.IsInvalidComplete}','${itemtask.StartTime}','${itemtask.GPSLocation}','${itemtask.CanPunchCard}','${itemtask.IsAllowCard}','${itemtask.IsSupplementCard}','${itemtask.IsMiss}',${itemtask.TaskChargeManID},'${itemtask.TaskChargeManName}','${itemtask.TaskChargeManHeaderImg}','${itemtask.IsAbnormal}','${itemtask.IsReport}',${itemtask.GongdanType},'${itemtask.GongdanTypeDesc}',${itemtask.GongdanID},${item.ID},${CheckStatusDesc},'${itemtask.TaskCompleteContent}','${itemtask.TaskCompleteTime}','','',0,'${itemtask.DeviceModel}','${itemtask.DeviceLocationPlace}');`;
                        db.executeSql({
                            name: 'prodemotest',
                            sql: tasksql,
                        }, function (ret, err) {
                            // console.log('插入Sys_PlanTask');
                            // console.log(JSON.stringify(ret));
                            // console.log(JSON.stringify(err));
                        });
                        if (itemtask.imgList != undefined && itemtask.imgList.length > 0) {
                            itemtask.imgList.forEach((itemimg, indeximg) => {
                                //插入Sys_File 表数据
                                let filesql = `INSERT INTO Sys_File (ID,TaskID,FilePath,PlanTaskID) VALUES (${itemimg.FileId},${itemimg.PatrolTaskID},'${itemimg.FilePath}',${item.ID});`;
                                db.executeSql({
                                    name: 'prodemotest',
                                    sql: filesql,
                                }, function (ret, err) {
                                });
                            });
                        }
                        //设备-工作标准
                        if (itemtask.standardList != undefined && itemtask.standardList.length > 0) {
                            itemtask.standardList.forEach((itembz, indexbz) => {
                                //插入Sys_TaskStandard 表数据
                                let standardsql = `INSERT INTO Sys_TaskStandard (TaskID,StandardID,CheckStatus,CheckUserID,CheckUserName,CheckTime,CheckLocation,StandardName,PlanTaskID,JobWay,JobWayContent,StandardContent) VALUES (${itembz.DeviceTaskID},${itembz.DeviceStandardID},${itembz.CheckStatus},${itembz.CheckUserID},'${itembz.CheckUserName}','${itembz.CheckTime}','${itembz.CheckLocation}','${itembz.StandardName}',${item.ID},${itembz.JobWay},'${itembz.JobWayContent}','${itembz.StandardContent}');`;
                                db.executeSql({
                                    name: 'prodemotest',
                                    sql: standardsql,
                                }, function (ret, err) {
                                });
                            });  
                        }
                    });
                }
            });

            if(that.configList!=undefined&&that.configList.length>0){
                //先执行删除权限-再执行插入-保持最新数据
                let delconfigsql=`DELETE FROM Sys_ProjectConfig WHERE PlanType=1`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: delconfigsql,
                }, function (ret, err) {
                });
                that.configList.forEach((item, index) => {
                    //插入Sys_ProjectConfig 表数据
                    let configsql = `INSERT INTO Sys_ProjectConfig (ProjectID,ConfigType,ConfigKey,ConfigContent,PlanType) VALUES (${item.ProjectId},'${item.ConfigType}','${item.ConfigKey}','${item.ConfigContent}',1);`;
                    db.executeSql({
                        name: 'prodemotest',
                        sql: configsql,
                    }, function (ret, err) {
                        // console.log('插入Sys_ProjectConfig');
                        // console.log(JSON.stringify(ret));
                        // console.log(JSON.stringify(err));
                    });
                });
            }
            return true;
        },
        do_create_tabel: function () {
            var that = this;
            //创建离线任务相关表
            //计划任务表
            db.executeSql({
                name: 'prodemotest',
                sql: 'CREATE TABLE Sys_Plan(ID int, DevicePlanName varchar(100),ProjectID int,ProjectName varchar(100),PlanType int, PlanTypeDesc varchar(50),TaskStatus int,TaskResultDesc varchar(50),OutTimeStatusDesc varchar(50),TaskStatusDesc varchar(50),StartTime DateTime,EndTime DateTime,CheckStartTime DateTime,CheckEndTime DateTime,TaskChargeManName varchar(100),WorkOrderType int,PatrolLineName varchar(255),count int,completeCount int,normalCount int,abnormalCount int,IsUpload int,UploadTime DateTime,IsAllowCard Boolean,IsMiss Boolean,WithLine int);'
            }, function (ret, err) {
                // console.log('Sys_Plan');
                // console.log(JSON.stringify(ret));
                // console.log(JSON.stringify(err));
            });
            //任务-工作记录表
            db.executeSql({
                name: 'prodemotest',
                sql: 'CREATE TABLE Sys_PlanTask(EncriptID varchar(50),ID int,ProjectName varchar(100),PatrolNumber varchar(50),PatrolID int, PatrolName varchar(255), RequireScan Boolean, CanProcessDirect Boolean,IsAllowUpload Boolean,IsAllowGPS Boolean,TaskStatus int,TaskResultDesc varchar(50),IsInvalidComplete Boolean,StartTime DateTime,GPSLocation varchar(255),CanPunchCard Boolean,IsAllowCard Boolean,IsSupplementCard Boolean,IsMiss Boolean,TaskChargeManID int,TaskChargeManName varchar(100),TaskChargeManHeaderImg varchar(2000),IsAbnormal Boolean,IsReport Boolean,GongdanType int,GongdanTypeDesc varchar(50),GongdanID int,PlanTaskID int,CheckStatus int,TaskCompleteContent ntext,TaskCompleteTime varchar(50),Longitude varchar(200),Latitude varchar(200),APPUpload int,DeviceModel varchar(100),DeviceLocationPlace varchar(200));'
            }, function (ret, err) {
            });
            //任务附件表
            db.executeSql({
                name: 'prodemotest',
                sql: 'CREATE TABLE Sys_File(ID int,TaskID int, FilePath varchar(2000),PlanTaskID int);'
            }, function (ret, err) {
            });
            //项目授权表
            db.executeSql({
                name: 'prodemotest',
                sql: 'CREATE TABLE Sys_ProjectConfig(ProjectID int,ConfigType varchar(100),ConfigKey varchar(100),ConfigContent varchar(500),PlanType int);'
            }, function (ret, err) {
            });
            //设备-工作标准表
            db.executeSql({
                name: 'prodemotest',
                sql: 'CREATE TABLE Sys_TaskStandard(TaskID int,StandardID int,CheckStatus int,CheckUserID int,CheckUserName varchar(100),CheckTime DateTime,CheckLocation varchar(500),StandardName varchar(500),PlanTaskID int,JobWay int,JobWayContent varchar(500),StandardContent varchar(500));'
            }, function (ret, err) {
                // console.log(JSON.stringify(ret));
                // console.log(JSON.stringify(err));
            });
        },
        doComplete(item){
            var that = this;
            if(item.completeCount!=item.count){
                api.toast({
                    msg: '存在未完成的工作点，请完成所有工作点后再进行提交。',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.confirm({
                title: '提示',
                msg: '完成任务后不能再修改工作记录，如需修改需要使用重新执行功能。确认要完成工作任务吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret) {
                    if (ret.buttonIndex == 1) {
                        //Type-类型：1-设备 3-安防巡更 4-环境保洁
                        var options = { action: 'taskcomplete', ID: item.ID, Type: 1 };
                        ns.post(options, function (succeed, data, err) {
                            if (succeed) {
                                if (data.status) {
                                    that.get_data();
                                }
                            } else {
                                api.toast({
                                    msg: err,
                                    duration: 2000,
                                    location: 'bottom'
                                });
                            }
                        })
                    }
                }
            });
        },
    },

});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    toast = new auiToast();
    db = api.require('db');   
    //创建prodemotest数据库
    db.openDatabase({
        name: 'prodemotest'
    }, function(ret, err) {
        if (!ret.status) {
            api.toast({
                msg: err,
                duration: 2000,
                location: 'bottom'
            });
        } 
        else{
            app.do_create_tabel();
        }
    });

    app.get_menuType();
    app.form.ID = api.pageParam.ID || 0;
    app.get_data();
    api.addEventListener({
        name: 'devicetaskcomplete'
    }, function(ret, err) {
        app.get_data();
    });
    // api.addEventListener({
    //     name: 'startplantaskdone'
    // }, function(ret, err) {
    //     app.get_data();
    // });
    api.addEventListener({
        name: 'do_open_add'
    }, function (ret, err) {
        app.open_add();
    });
    api.addEventListener({
        name: 'do_open_select'
    }, function (ret, err) {
        app.open_select();
    });

    //在线-离线模式切换
    api.addEventListener({
        name: 'do_change_line'
    }, function (ret, err) {
        app.open_change_line();
    });
    
    // ns.init_pull(true,true);
    ns.init_pull();
};

